package xiaobange.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import xiaobange.common.BaseConText;
import xiaobange.common.R;
import xiaobange.entity.Orders;
import xiaobange.service.OrdersService;

import java.util.Date;

@RestController
@RequestMapping("order")
public class OrdersController {
        //开始时间
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startTime;
    // 结束时间
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;
    @Autowired
    private OrdersService ordersService;

    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.Submit(orders);
        return R.success("下单成功");
    }

    /**
     *用户端订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page , int pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getUserId , BaseConText.getThreadSessionID());
        lambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(ordersPage, lambdaQueryWrapper);
        return R.success(ordersPage);
    }


    /**
     * 管理端订单查看
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> adminPage(int page , int pageSize , Long number , String beginTime ,String endTime){
        Page<Orders> ordersPage = new Page<>(page , pageSize);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(number != null ,Orders::getNumber , number);
        lambdaQueryWrapper.le(beginTime != null , Orders::getOrderTime , beginTime);
        lambdaQueryWrapper.lt(endTime != null , Orders::getOrderTime , endTime);
        ordersService.page(ordersPage , lambdaQueryWrapper);
        return R.success(ordersPage);
    }


    /**
     * 修改配送状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> Put(@RequestBody Orders orders){
        if (orders.getId() == null || orders.getStatus() == null){
            return R.error("操作失败！");
        }
        Orders ordersData = ordersService.getById(orders);
        ordersData.setStatus(orders.getStatus());
        ordersService.updateById(ordersData);
        return  R.success("成功");
    }
}
